package com.bocloud.cmp.server.app.scheduler;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.entity.app.resource.Registry;
import com.bocloud.cmp.enums.app.CommonEnum.Status;
import com.bocloud.cmp.interfaces.app.resource.RegistryService;
import com.bocloud.cmp.service.utils.RegistryUtil;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.Result;
import com.bocloud.common.utils.ListTool;
import com.bocloud.coordinator.cache.LeaderShip;

/**
 * 仓库状态守护进程
 * 
 * @author Zaney
 * @data:2017年3月24日
 * @describe:
 */
public class RegistryDaemon extends Thread {
	private static Logger logger = LoggerFactory.getLogger(RegistryDaemon.class);
	private boolean stop = false;
	private RegistryService registryService;

	public RegistryDaemon(RegistryService registryService) {
		super();
		this.registryService = registryService;
	}

	public void run() {
		while (!stop) {
			try {
				Thread.sleep(1000 * 60 * 30);
			} catch (InterruptedException e) {
				logger.error("Registry daemon is　intercepted", e);
				continue;
			}
			if (!LeaderShip.isLeader()) {
				if (logger.isDebugEnabled()) {
					logger.debug("I am not leader! skip this loop!");
				}
				continue;
			}
			try {
				// 1、查询所有非删除的仓库信息
				List<Registry> registrys = registryService.getRegistrys();
				if (ListTool.isEmpty(registrys)) {
					if (logger.isDebugEnabled()) {
						logger.warn("check registry status, but no registries exist!");
					}
					continue;
				}
				HttpClient client = new HttpClient();
				for (Registry registry : registrys) {
					// 2、获取仓库的数据库中的状态
					String status = registry.getStatus();
					// 如果是锁定状态不允许操作
					if (Integer.valueOf(status) == Status.LOCK.ordinal()) {
						continue;
					}
					// 3、获取仓库在服务器端的状态
					Result healthResult = RegistryUtil
							.checkRegistry(registry.getAddress() + ":" + registry.getRegistryPort(), client);
					if (healthResult.isSuccess()) {
						if (Integer.valueOf(status) != Status.NORMAL.ordinal()) {
							String[] fields = { "status" };
							registry.setStatus(String.valueOf(Status.NORMAL.ordinal()));
							registryService.updateWithField(registry, fields);
						}
					} else {
						if (Integer.valueOf(status) == Status.NORMAL.ordinal()) {
							String[] fields = { "status" };
							registry.setStatus(String.valueOf(Status.ABNORMAL.ordinal()));
							registryService.updateWithField(registry, fields);
						}
					}
				}
			} catch (Exception e1) {
				logger.warn("Registry Daemon Exception:", e1);
				continue;
			}
		}
	}

	public void stopDeamon() {
		this.stop = true;
	}

	public void startDeamon() {
		this.stop = false;
	}

}
